<?php
require $_SERVER['DOCUMENT_ROOT'].'/../_core/common.php';

//权限验证
if( Role::init() == false ){
	exit('没有权限');
}

$db = new DB();

$id = isset($_POST['id']) ? intval($_POST['id']) : 0;
$name = isset($_POST['name']) ? h($_POST['name']) : '';
$modelid_arr = isset($_POST['modelid']) ? $_POST['modelid'] : 0;
$created = time();
$updated = $created;

if( $id < 2 || $name == '' ){
	echo '<script>alert("参数有误！");window.history.go(-1);</script>';
	exit;
}

//检测职务
$group_id_sql = 'select id from users_group where id='.$id.' and is_del=1 limit 1';
$group_id_rs = $db->query($group_id_sql)->getOne();
if( $group_id_rs['id'] < 2 ){
	echo '<script>alert("参数有误！");window.history.go(-1);</script>';
	exit;
}

//检测重复
$group_name_sql = 'select id from users_group where name="'.$name.'" and is_del=1 limit 1';
$group_name_rs = $db->query($group_name_sql)->getOne();
if( $group_name_rs['id'] > 0 && $group_name_rs['id'] != $id  ){
	echo '<script>alert("修改失败，职务 '.$name.' 已经存在！");window.history.go(-1);</script>';
	exit;
}

//更新职务名称
$group_data = array('name'=>$name);
$db->table('users_group')->where('id='.$id)->update($group_data)->run();

//删除旧权限记录
$db->table('roles_group')->where('groupid='.$id)->delete()->run();

//插入新权限
foreach( $modelid_arr as $modelid ){
	if( intval($modelid) > 0 ){
		$data=array('groupid'=>$id,
					'modelid'=>intval($modelid),
					'created'=>$created,
					'updated'=>$updated,
					);
		$db->table('roles_group')->insert($data)->run();
	}
}

echo '<script>alert("修改权限成功！");window.location.href="/www/admin/role/position_lists.php";</script>';
exit;